import React, { useRef } from 'react'
import { useDispatch } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import { addGoods } from '../store/slice/goodsSlice';

export default function AddGoods() {
    const dispatch = useDispatch();
    const navigate = useNavigate();
    const gnameRef = useRef();
    const priceRef = useRef();
    const addHandler = (e)=>{
        e.preventDefault();
        // 1. 获取表单输入的内容
        let gname = gnameRef.current.value.trim();
        let price = +priceRef.current.value.trim();
        let goods = {gname,price}
        // 调用dispatch，添加数据到store
        dispatch(addGoods(goods))
        // 跳转页面到 商品列表页
        navigate('/goods_list')
    }
    return (
        <div>
            <form action="" onSubmit={addHandler}>
                <p>商品名: <input type="text" ref={gnameRef} name="" id="" /></p>
                <p>价格: <input type="text" ref={priceRef} name="" id="" /></p>
                <p><button>添加商品</button></p>
            </form>
        </div>
    )
}
